<?php

namespace app\model;

use think\Model;
use think\model\relation\HasMany;
use think\model\relation\HasOne;

class User extends Model
{
    public function findOrRegister(): array
    {
        $mobile = request()->post("mobile");
        $account = $this->where(['mobile' => $mobile])->find();
        if (empty($account)) {
            //注册成为会员
            $this->save([
                'mobile' => $mobile,
                'username' => $mobile,
                'balance' => 0,
                'state' => 1,
                'is_del' => 1,
            ]);
            $account = $this->where(['mobile' => $mobile])->find();
        } else if ($account['state'] == 2) throw new \Exception("账号存在异常，请联系服务商！", 7045);
        else if ($account['is_del'] == 0) {
            //恢复会员
            $account->is_del = 1;
            $account->save();
        }
        return $account->toArray() ?? $this->toArray();
    }

    public function car(): HasMany
    {
        return $this->hasMany(UserCar::class, "uid");
    }

    public function detail()
    {
        $id = request()->param("id");
        $data = $this->with(['car'])->where(['id' => $id])->findOrFail();
        $data->balance = (float)(bcdiv($data->balance, 100, 2));
        //获取月底到期的积分数
        $last_time = date("Y-m-t 23:59:59");
        $lastScore = app(UserValidateBalance::class)->where("uid", $id)->where('last_time', $last_time)->value("balance");
        if (!empty($lastScore))
            $data->lastScore = (float)(bcdiv($lastScore, 100, 2));
        else $data->lastScore = 0;
        return $data;
    }
}
